package com.atguigu.edu.entity.excelUtil;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.edu.entity.Subject;
import com.atguigu.edu.service.SubjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;

/**
 * excel监听方法 包含一二级菜单添加功能
 */
@Slf4j
public class ExcelEventListener extends AnalysisEventListener<SubjectData> {

    private SubjectService subjectService;

    //    有参构造器 可以注入spring管理的bean 注入subjectService
    public ExcelEventListener(SubjectService subjectService) {
        this.subjectService = subjectService;
    }

    //按行读取数据
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
//        查询名称相同 且parentId为0的 为一级菜单 如不存在则添加 并将id 作为二级菜单的parentId
        Subject subject = existsOneType(subjectData.getOneSubjectName());
        if (subject == null) {
            subject = new Subject();
//            使用雪花算法生成id
            subject.setTitle(subjectData.getOneSubjectName());
            subject.setSort(0);
            subject.setParentId("0");
            subjectService.save(subject);
        }
        log.debug(subject.toString());

//        根据parentId和名称查询二级菜单是否存在 如存在 则不添加
        Subject subject1 = existsTwoType(subjectData.getTwoSubjectName(), subject.getId());
        if (subject1 == null) {
            subject1 = new Subject();
//            sub的id作为二级菜单的parentId
            subject1.setParentId(subject.getId());
            subject1.setTitle(subjectData.getTwoSubjectName());
            subjectService.save(subject1);

        }
        log.debug(subject1.toString());
        subject = null;
        subject1 = null;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
    }

    /**
     * 查询一级菜单是否存在
     *
     * @param oneTitle 一级标题 用于方法区分
     * @return
     */
    public Subject existsOneType(String oneTitle) {
        QueryWrapper<Subject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("title", oneTitle);
        queryWrapper.eq("parent_id", "0");
        Subject subject = subjectService.getOne(queryWrapper);
        queryWrapper = null;
        return subject;
    }

    /**
     * 查询二级菜单是否重复
     *
     * @param twotitle 标题
     * @param parentId 父菜单ID
     * @return
     */
    public Subject existsTwoType(String twotitle, String parentId) {
        QueryWrapper<Subject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("title", twotitle);
        queryWrapper.eq("parent_id", parentId);
        Subject subject = subjectService.getOne(queryWrapper);
        queryWrapper = null;
        return subject;
    }
}
